<?php

namespace App\Http\Controllers;

use App\Models\Permission;
use App\Models\UsersExtraPermission;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Symfony\Component\HttpFoundation\JsonResponse;

class PermissionsController extends Controller
{

    protected $allow_method = [
        "GET",
        "POST",
        "PUT",
        "DELETE",
        "OPTION"
    ];


    /**
     * @param  Request  $request
     * @return JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        //

        $permission = Permission::where([['parentid',0],['status',1]])->with('children')->select(['id','parentid','name as label','method','status'])->get();

        return Success(10100, $permission);
    }

    public function permissionSelect(Request $request): JsonResponse
    {
        //
        $id = $request->get('id');
        $parentid= $request->get('parentid');
        if($parentid){
            $permission = Permission::where('parentid',$parentid)->get();
        }else{
            $permission = Permission::whereIn('id',$id)->get();
        }


        return Success(10100, $permission);
    }



    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return JsonResponse
     */
    public function store(Request $request): JsonResponse
    {
        //
        $name = $request->get("name");
        $api_route = $request->get("api_route");
        $web_route = $request->get("web_route");
        $method = $request->get("method");
        $desc = $request->get("desc");
        $no = $request->get("no");
        $is_need_auth = $request->get("is_need_auth") == "true" ? 1 : 0;
        $is_system_menu = $request->get("is_system_menu") == "true" ? 1 : 0;
        $parentid = $request->get("parentid");

        if (!in_array($request->get("method"), $this->allow_method)) {
            return Failed(10301, ["File" => "PermissionsController", "line" => __LINE__, "filed_error" => ["Method" => $this->allow_method]]);
        }

        $data = [
            "name" => $name,
            "api_route" => $api_route,
            "web_route" => $web_route,
            "method" => $method,
            "desc" => $desc,
            "no" => $no,
            "is_need_auth" => $is_need_auth,
            "status" => 1,
            "is_system_menu" => $is_system_menu,
            "parentid" => $parentid,
            "updated_at" => date("Y-m-d H:i:s"),
            "created_at" => date("Y-m-d H:i:s")
        ];


        if (!$name || !$parentid === null || !$api_route || !$method) {
            return Failed(10002, ["File" => "PermissionController", "line" => __LINE__, "need_filed" => ['name', 'api_route', 'method', 'parentid']]);
        }
        $permission = Permission::where([["name", $name], ["api_route", $api_route], ["method", $method], ["status", 1]])->first();

        if ($permission) {
            return Failed(10006, ['File' => "PermissionsController", "line" => __LINE__, "resource_same" => ["name" => $name, "api_route" => $api_route, "method" => $method, "status" => 1]]);
        }
        if (!Permission::create($data)) {
            return Failed(10001, ['File' => "PermissionsController", "line" => __LINE__]);
        }

        return Success(10000, []);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return JsonResponse
     */
    public function show(int $id): JsonResponse
    {
        //
        if(!$id){
            return Failed(10002, ["File"=>"PermissionsController","line"=>__LINE__,"need_filed" => ['id']]);
        }
        $permission = Permission::where([["id",$id]])->first();
        if(!$permission){
            return Failed(11101, ["File"=>"PermissionsController","line"=>__LINE__,"resource" => "not_found"]);
        }
        return Success(11100,["data"=>$permission]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return JsonResponse
     */
    public function update(Request $request, int $id): JsonResponse
    {
        //
        if (!$id) {
            return Failed(10002, ["File" => "PermissionsController", "line" => __LINE__, "need_filed" => ['id']]);
        }

        $permission = Permission::where([["id", $id], ['status', 1]])->first();
        if (!$permission) {
            return Failed(10005, ["File" => "PermissionsController", "line" => __LINE__, "resource" => "not_found"]);
        }
        if (!in_array($request->get("method"), $this->allow_method)) {
            return Failed(10301, ["File" => "PermissionsController", "line" => __LINE__, "filed_error" => ["Method" => $this->allow_method]]);
        }
        $data = [
            "parentid" => $request->get("parentid"),
            "name" => $request->get("name"),
            "api_route" => $request->get("api_route"),
            "web_route" => $request->get("web_route"),
            "method" => $request->get("method"),
            "desc" => $request->get("desc"),
            "no" => $request->get("no"),
            "is_need_auth" => $request->get("is_need_auth"),
            "is_system_menu" => $request->get("is_system_menu"),
            "updated_at" => date("Y-m-d H:i:s"),
        ];
        if (!Permission::where("id", $id)->update($data)) {
            return Failed(11010, ["File" => "PermissionsController", "line" => __LINE__, "updated_error" => "修改失败"]);
        }
        return Success(11000, ["File" => "PermissionsController", "line" => __LINE__, "updated_success" => "修改成功"]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(int $id): \Illuminate\Http\JsonResponse
    {
        if (!$id) {
            return Failed(10002, ["File" => "PermissionsController", "line" => __LINE__, "need_filed" => ['id']]);
        }
        $permission = Permission::where([["id", $id], ['status', 1]])->first();
        if (!$permission) {
            return Failed(10005, ["File" => "PermissionsController", "line" => __LINE__, "resource" => "not_found"]);
        }
        $permission->status = 0;
        $permission->updated_at = date("Y-m-d H:i:s");
        if (!$permission->save()) {
            return Failed(10007, ["File" => "PermissionsController", "line" => __LINE__, "resource" => "delete_failed"]);
        }
        return Success(10700, ["File" => "PermissionsController", "line" => __LINE__, "resource" => "delete_success"]);
    }

    public function bindUser(Request $request,int $user_id)
    {

        $perArr = $request->get("permissionArr");
        if(!$user_id || empty($perArr)){
            return Failed(10002, ["File"=>"PermissionsController","line"=>__LINE__,"need_filed" => ['user_id','permissionsArr']]);
        }
        UsersExtraPermission::where("user_id",$user_id)->delete();
        $data = [];
        foreach ($perArr as $key => $vo) {
            $data[$key] = [
                "user_id" => $user_id,
                "permission_id" => $vo,
                "updated_at" => date("Y-m-d H:i:s"),
                "created_at" => date("Y-m-d H:i:s"),
            ];
        }
        try {
            if (!UsersExtraPermission::insert($data)) {
                return Failed(10001, ['File' => "PermissionsController", "line" => __LINE__, "msg" => "用户额外权限添加失败"]);
            }
        } catch (\Illuminate\Database\QueryException $ex) {
            return Failed(10006, ['File' => "PermissionsController", "line" => __LINE__, "resource_same" => $data]);
        }
        return Success(10000, []);
    }
}
